package com.fourth.rabbit;

import com.alibaba.fastjson.JSON;
import com.fourth.config.RabbitConfiguration;
import com.fourth.service.UbOrderService;
import com.fourth.service.UbStockService;
import com.ljx.entity.Order;
import com.ljx.entity.Stock;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Iterator;
import java.util.List;

/**
 * @author Mr.ma
 * @since 2023/3/11 15:12
 **/
@Component
@Slf4j
public class DlxConsumer {

    @Resource
    private UbOrderService ubOrderService;

    @Resource
    private UbStockService ubStockService;

    @RabbitListener(queues = RabbitConfiguration.DLX_QUEUE_NAME)
    public void consumeDL(String msg, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long tag) throws Exception {
        List<Order> orderByCode = ubOrderService.getOrderByCode(msg);
        if (orderByCode == null){
            channel.basicAck(tag,true);
            return;
        }

        if (orderByCode.get(0).getState() == 1){
            ubOrderService.changeState(orderByCode.get(0).getCode(), 3);
            // 回退商品库存
            Iterator<Order> iterator = orderByCode.iterator();
            while (iterator.hasNext()){
                Order order = iterator.next();
                Stock stock = ubStockService.selectByGoodsId(order.getGoodsid());
                stock.setResidue(stock.getResidue() + order.getNum());
                ubStockService.updateStock(stock);
            }
        }

        channel.basicAck(tag,true);
    }


}
